import { Controller, Context, Post, Get, Delete, Use, sfn } from "nb2";
import { ResBody, Token } from "../common/model.js";
import { prisma } from "../prisma.js";
import { handleAuth } from "../common/handleAuth.js";

@Controller("comment")
export class Comment {
  @Use(handleAuth)
  @Delete("delete/:cid")
  async [sfn()](ctx: Context) {
    const cid = Number(ctx.params.cid);
    const comment = await prisma.comment.delete({ where: { id: cid } });
    ctx.json<ResBody>({ code: 200, msg: "删除成功", result: comment.id });
  }

  @Get("query")
  async [sfn()](ctx: Context) {
    let page = Number(ctx.query.page) || 1;
    let page_size = Number(ctx.query.page_size) || 10;
    let gid = Number(ctx.query.gid);

    const total = await prisma.comment.count({
      where: { goodsId: gid, parentId: null },
    });

    const comments = await prisma.comment.findMany({
      where: { goodsId: gid, parentId: null },
      take: page_size,
      skip: (page - 1) * page_size,
      orderBy: { createAt: "desc" },
      include: { user: true },
    });

    let result = await Promise.all(
      comments.map(async (item) => {
        const replys = await prisma.comment.findMany({
          where: {
            parentId: item.id,
            goodsId: item.goodsId,
          },
          include: { user: true, toUser: true },
          orderBy: { createAt: "desc" },
        });
        return { ...item, replys };
      })
    );

    ctx.json<ResBody>({
      code: 200,
      result,
      total,
    });
  }

  @Use(handleAuth)
  @Post("create")
  async [sfn()](ctx: Context) {
    const token = ctx.custom.token as Token;
    const body = await ctx.body("json");
    const comment = await prisma.comment.create({
      data: {
        parentId: body.parent_id,
        userId: token.uid,
        toUserId: body.to_uid,
        content: body.content,
        goodsId: body.gid,
      },
    });
    let msg = body.to_uid ? "回复成功" : "评论成功";
    ctx.json<ResBody>({ code: 200, msg, comment });
  }
}
